package cn.sunchis.pvuv.sdk.config;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.servlet.DispatcherServlet;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.sunchis.pvuv.sdk.model.Pvuv;

/**
 * 增加PV/UV统计扩展点
 * @Author 许亮
 * @Create 2018-6-29 14:57:29
 */
@SuppressWarnings("serial")
public class PvuvDispatcherServlet extends DispatcherServlet {
	@Autowired
	private Environment environment;
	@Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
	
	private ObjectMapper jsonObjectMapper = new ObjectMapper();
	
	@Override
	protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
		super.doDispatch(request, response);
		
		newVisit(request);
	}
	
	private void newVisit(HttpServletRequest request) {
		Pvuv pvuv = new Pvuv();
		pvuv.setSys("Java应用");
		pvuv.setCom(environment.getProperty("spring.application.name"));
		pvuv.setHost(environment.getProperty("COMPUTERNAME") + ":" + environment.getProperty("server.port", Integer.class));
		pvuv.setUrl(request.getRequestURI());
		pvuv.setSid(request.getParameter("userId"));
		pvuv.setStamp(new Date());
		
		try {
			kafkaTemplate.send(PvuvServiceConfig.KAFKA_PVUV_TOPIC, "pvuv", jsonObjectMapper.writeValueAsString(pvuv));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
	}
}
